//
//  MACommonUtils.m
//  GNAPP
//
//  Created by zzp on 2019/1/15.
//  Copyright © 2019年 zzp. All rights reserved.
//

#import "MACommonUtils.h"


@implementation MACommonUtils
+ (MKMapRect)mapRectForOverlays:(NSArray *)overlays
{
    if (overlays.count == 0)
    {
        NSLog(@"%s: 无效的参数.", __func__);
        return MKMapRectMake(0, 0, 0, 0);
    }
    
    MKMapRect mapRect;
    
    MKMapRect *buffer = (MKMapRect*)malloc(overlays.count * sizeof(MKMapRect));
    
    [overlays enumerateObjectsUsingBlock:^(id<MKOverlay> obj, NSUInteger idx, BOOL *stop) {
        buffer[idx] = [obj boundingMapRect];
    }];
    
    mapRect = [self mapRectUnion:buffer count:overlays.count];
    
    (void)(free(buffer)), buffer = NULL;
    
    return mapRect;
}
+ (MKMapRect)mapRectUnion:(MKMapRect *)mapRects count:(NSUInteger)count
{
    if (mapRects == NULL || count == 0)
    {
        NSLog(@"%s: 无效的参数.", __func__);
        return MKMapRectMake(0, 0, 0, 0);;
    }
    
    MKMapRect unionMapRect = mapRects[0];
    
    for (int i = 1; i < count; i++)
    {
        unionMapRect = [self unionMapRect1:unionMapRect mapRect2:mapRects[i]];
    }
    
    return unionMapRect;
}
+ (MKMapRect)unionMapRect1:(MKMapRect)mapRect1 mapRect2:(MKMapRect)mapRect2
{
    CGRect rect1 = CGRectMake(mapRect1.origin.x, mapRect1.origin.y, mapRect1.size.width, mapRect1.size.height);
    CGRect rect2 = CGRectMake(mapRect2.origin.x, mapRect2.origin.y, mapRect2.size.width, mapRect2.size.height);
    
    CGRect unionRect = CGRectUnion(rect1, rect2);
    
    return MKMapRectMake(unionRect.origin.x, unionRect.origin.y, unionRect.size.width, unionRect.size.height);
}
@end
